#include "Precompile.h"
#include "DX11TextureCube.h"
#include "DX11RenderSystem.h"

namespace Graphics{
	DX11TextureCube::DX11TextureCube(std::string& top, std::string& bottom, std::string& left, std::string& right, std::string& front, std::string& back, RenderContext* handle):
		TextureCube(top,bottom,left,right,front,back,handle),m_resourceView(NULL){

		// Load textures
		Utility::ImageDescriptionPtr imageDesc[6];
		
		// Load textures
		D3D11_SUBRESOURCE_DATA subResources[6];
		ZeroMemory(subResources,sizeof(D3D11_SUBRESOURCE_DATA)*6);
		for(unsigned int i=0; i<6; i++){
			std::string filePath = Core::GeneralSettings::findFilePath(m_filenames[i]);
			imageDesc[i] = Utility::ImageLoader::loadImage(m_filenames[i]);

			subResources[i].pSysMem = imageDesc[i]->m_data;
			subResources[i].SysMemPitch = imageDesc[i]->m_dataPitch;
			subResources[i].SysMemSlicePitch = 0;
		}

		D3D11_TEXTURE2D_DESC tex2dDesc;
		ZeroMemory(&tex2dDesc,sizeof(D3D11_TEXTURE2D_DESC));
		tex2dDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
		tex2dDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
		tex2dDesc.ArraySize = 6;
		tex2dDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
		tex2dDesc.MipLevels = 1;
		tex2dDesc.SampleDesc.Count = 1;
		tex2dDesc.Width = imageDesc[0]->m_width;
		tex2dDesc.Height = imageDesc[0]->m_height;

		HRESULT hr;
		hr = handle->m_handle->CreateTexture2D(&tex2dDesc,subResources,&m_texArray);
		if(FAILED(hr)){
			LOG_ERROR("Failed in creating texture array.");
			assert(0);
			return;
		}
		
		D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
		srvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
		srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
		srvDesc.TextureCube.MipLevels = 1;
		srvDesc.TextureCube.MostDetailedMip = 0;

		hr = handle->m_handle->CreateShaderResourceView(m_texArray,&srvDesc,&m_resourceView);
		if(FAILED(hr)){
			LOG_ERROR("Failed in creating shader resource view.");
			assert(0);
		}
	}
	
	DX11TextureCube::~DX11TextureCube(){
		if(m_texArray)
			m_texArray->Release();
		if(m_resourceView)
			m_resourceView->Release();
	}

	void DX11TextureCube::setTexture(RenderContext* context){
		DX11RenderContext* ctx = (DX11RenderContext*)context;

		ctx->m_context->PSSetShaderResources(0,1,&m_resourceView);
	}
}